import type { GreasyForkElements } from '../../../../../../../../types/constants/personalization/greasy_fork'
import type { IUserData } from '../module/script_processor/types'
import { PageHandler } from '../../../../../../../../lib/page_handler'
import {
  AppStyleCollections,
  BodyClasses,
  PAGE_ELEMENTS,
  PROJECT_PREFIX,
  SUPPORTED_PLATFORMS,
} from '../../../../../../../../types/constants'
import { StorageProcessor } from '../module/storage_process'
import { CommonPage } from './common'

// 测试链接：
// 1）https://greasyfork.org/zh-CN/users
// 2）https://greasyfork.org/zh-CN/users?q=111
export class UsersPage {
  elements: GreasyForkElements = PAGE_ELEMENTS[SUPPORTED_PLATFORMS.GREASY_FORK]
  private static instance: UsersPage
  private pageHandler: PageHandler = PageHandler.getInstance()
  private storageProcessor: StorageProcessor = StorageProcessor.getInstance()
  private commonPage: CommonPage = CommonPage.getInstance()
  private readonly selector: string = '#browse-user-list li'
  private readonly processedAttr: string = 'processed-users'

  /**
   * 获取单例实例
   */
  public static getInstance(): UsersPage {
    if (!UsersPage.instance) {
      UsersPage.instance = new UsersPage()
    }
    return UsersPage.instance
  }

  init(): void {
    $(this.selector).each((index, element) => {
      const $element = $(element)

      // 检查是否已经处理过（避免重复处理）
      if ($element.data(this.processedAttr))
        return

      $element.data(this.processedAttr, true)

      const $userLink = $element.find('.user-link')
      const userId = this.pageHandler.services.greasyFork.getUserId($userLink)
      const userTypes = this.storageProcessor.getUserType(userId)

      // 添加序号
      this.pageHandler.pages.base.addIndex(index, $element)

      // 隐藏用户链接
      $userLink.addClass(AppStyleCollections.Hide.ELEMENT)

      // 添加用户头像
      const data: IUserData = {
        author: $userLink.text().trim(),
        authorUrl: $userLink.attr('href') || '',
      }
      this.pageHandler.features.user.addAvatar($element, data)

      // 添加用户类型徽章（！！！在用户头像后面）
      const $avatarContainer = $element.find(`.${AppStyleCollections.Body.AVATAR_CONTAINER}`)
      if (userTypes.length > 0 && $avatarContainer.length) {
        this.pageHandler.features.user.addUserTypeBadge($avatarContainer, userTypes)
      }

      // 复制已有徽章
      const $scriptIndexWrapper = $element.find(`#${BodyClasses.INDEX_CONTAINER}`)
      const $badges = $element.find('> .badge')
      if ($badges.length && $scriptIndexWrapper.length) {
        if ($badges.hasClass('badge-banned')) {
          this.pageHandler.features.badge.addBadge(
            $scriptIndexWrapper,
            'badge-banned',
            '已封禁',
            { backgroundColor: '#ff0000e6' },
          )
        }
        else if ($badges.hasClass('badge-author')) {
          this.pageHandler.features.badge.addBadge(
            $scriptIndexWrapper,
            'badge-author',
            '作者',
          )
        }
        $badges.remove()
      }
    })
  }

  getMainStyles(): string {
    return `
.sidebarred {
  padding-top: 0 !important;
  background-color: var(--${PROJECT_PREFIX}-theme-bg-base) !important;
  
  .user-list-header {
    h2 {
      color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
      margin-left: 16px !important;
    }
  }

  #browse-user-list {
    background-color: var(--${PROJECT_PREFIX}-theme-bg-base) !important;
    border: none !important;
    box-shadow: none !important;
    margin-top: 0 !important;
    color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
    
    a {
      ${this.commonPage.linkStyles()}
    }
    
    /* 结果列表 */
    li {
      grid-template-columns: auto 1fr;
      grid-template-rows: auto auto; /* 行数 */
      grid-template-areas:
        "index index"
        "avatar article";
      ${this.commonPage.baseListStyles()}
    }
  }
}
`
  }
}
